package main

import (
	"context"
	"fmt"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"strings"
	"time"
)

func main222() {
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("minioadmin", "minioadmin", "")),
		config.WithEndpointResolverWithOptions(aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
			return aws.Endpoint{
				URL: "http://store.sourcefind.cn:9009",
			}, nil
		})),
		config.WithRegion("cn-north-1"),
	)
	if err != nil {
		return
	}
	client := s3.NewFromConfig(cfg, func(o *s3.Options) {
		o.UsePathStyle = true //https://s3.amazonaws.com/BUCKET/KEY
	})

	// 打印所有的桶
	result, err := client.ListBuckets(context.TODO(), &s3.ListBucketsInput{})
	if err != nil {
		return
	}
	for _, bucket := range result.Buckets {
		fmt.Println(*bucket.Name)
	}

	// 2. 生成预签名 URL（12小时有效期）
	bucketName := "dasapp-commhub-forum" // 替换为你的桶名
	objectKey := "forum/liuysh/1758608302275/1758608302929.png"
	presignedURL, err := generatePresignedURL(client, bucketName, objectKey, 24*time.Hour)
	if err != nil {
		fmt.Printf("生成预签名URL失败: %v\n", err)
		return
	}
	customURL := strings.Replace(presignedURL, "http://store.sourcefind.cn:9009", "http://store.sourcefind.cn:5666", 1)

	fmt.Printf("12小时可访问的URL: %s\n", presignedURL)
	fmt.Printf("12小时可访问的URL: %s\n", customURL)
}

// 生成预签名URL
func generatePresignedURL(client *s3.Client, bucketName, objectKey string, duration time.Duration) (string, error) {
	// 创建预签名客户端
	presignClient := s3.NewPresignClient(client)

	// 创建 GetObject 请求
	presignRequest, err := presignClient.PresignGetObject(context.TODO(), &s3.GetObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
	}, func(opts *s3.PresignOptions) {
		opts.Expires = duration // 设置有效期
	})
	if err != nil {
		return "", fmt.Errorf("创建预签名请求失败: %v", err)
	}

	return presignRequest.URL, nil
}
